package com.uni.sofia.reader.model
{
	import com.uni.sofia.reader.interfaces.StateManager;
	import com.uni.sofia.reader.utils.UrlParser;
	
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.utils.Timer;
	
	import mx.events.BrowserChangeEvent;
	import mx.managers.BrowserManager;
	import mx.managers.IBrowserManager;

	/**
	 * The class responsible for managing the state of the application 
	 **/ 
	public class ApplicationManager //implements StateManager
	{
		public static const LIBRARY_STATE:String = "library";
		public static const MAGAZINE_STATE:String = "magazine";
		public static var DEFAULT_STATE:String = ApplicationManager.LIBRARY_STATE;
		
		[Bindable]
		public var state:String;
		
		private var lastUrl:String = null;
		
		private var timer:Timer;
		private static const TIMER_INTERVAL:int = 200;
		private var browserManager:IBrowserManager;
		private var _urlParser:UrlParser = new UrlParser();
		
		/**
		 * Constructor of the class. Creates a <code>IBrowserManager</code> instance for managing the deep linking mechanics. Also creates a <code>Timer</code> instance for checking the url of the browser because <code>BrowserManager</code> is unreliable on all browsers
		 *  
		 **/
		public function ApplicationManager()
		{
			state = ApplicationManager.DEFAULT_STATE;
			
			browserManager = BrowserManager.getInstance();
			browserManager.init();
			browserManager.setFragment(_urlParser.stateToUrl(ApplicationManager.DEFAULT_STATE));
			
			timer = new Timer(ApplicationManager.TIMER_INTERVAL);
			timer.addEventListener(TimerEvent.TIMER, updateUrl);
			timer.start();
		}

		/**
		 *Invoked in a short interval of time, checks the current URL of the browser. If that url changes, it will change the state of the browser. <code>IBrowserManager</code> will be also useful for deep linking, but unfortunately it does not work with browsers like Chrome, Opera, Safari and See Monkey.
		 * 
		 * @param event
		 * 		Timer event, nothing special 
		 */
		private function updateUrl(event:TimerEvent = null):void
		{
			var url:String = ExternalInterface.call("getUrl");
			if(lastUrl == null || lastUrl != url)
			{
				state = _urlParser.parseState(url);
				lastUrl = url;
			}
		}
		
        /**
		 * Sets the url in the link bar of the browser
		 * @param url
		 * 		the url to be set
		 */ 
		public function setUrl(url:String):void
		{
			browserManager.setFragment(url);
		}
	}
}